package pub.cleangao.codegen.enquiry.postgres;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import pub.cleangao.codegen.GenConfigHolder;
import pub.cleangao.codegen.enquiry.ColumnEnquiry;
import pub.cleangao.codegen.enquiry.TableEnquiry;
import pub.cleangao.codegen.enquiry.TableInfo;
import pub.cleangao.codegen.util.ClassField;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PostgresTableEnquiry extends TableEnquiry {

    private static final String SHOW_TABLE_SQL =
            """
            SELECT  t.schemaname, t.tablename, t2.cmt FROM  pg_tables t LEFT JOIN   (  SELECT relname as tablename, obj_description(oid) AS cmt  FROM pg_class C  WHERE relkind='r' AND relname NOT LIKE 'pg_%%' AND relname NOT LIKE 'sql_%%' AND relchecks=0   ORDER BY relname  ) t2 ON t.tablename = t2.tablename WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema' %s %s
            """;

    public PostgresTableEnquiry(GenConfigHolder config, ColumnEnquiry columnEnquiry) {
        super(config, columnEnquiry);
    }

    @Override
    public String getShowTablesSql() {
        String schema = config.getSchemaName();
        if (schema == null) {
            schema = "";
        }
        if (StringUtils.isNotBlank(schema)) {
            schema = String.format("AND schemaname = '%s'", schema);
        }
        List<String> tableNames = wrapTableNames();
        String and = "";
        if (!tableNames.isEmpty()) {
            and = String.format("AND t.tablename in (%s)", String.join(",", tableNames));
        }
        return String.format(SHOW_TABLE_SQL, schema, and);
    }

    @Override
    public TableInfo buildTableInfo(Map<String, Object> tableMap) {
        TableInfo tableInfo = new TableInfo();
        tableInfo.setSchema(ClassField.convertString(tableMap.get("SCHEMANAME")));
        tableInfo.setTableName(ClassField.convertString(tableMap.get("TABLENAME")));
        tableInfo.setTableNameHyphen(tableInfo.getTableName().replace("_","-"));
        tableInfo.setComment(ClassField.convertString(tableMap.get("CMT")));
        return tableInfo;
    }

    private List<String> wrapTableNames() {
        if (CollectionUtils.isEmpty(this.schemaTables)) {
            return Collections.emptyList();
        }
        return this.schemaTables.stream()
                .map(this::wrapValue)
                .collect(Collectors.toList());
    }

    private String wrapValue(String tableName) {
        return String.format("'%s'", tableName);
    }
}
